﻿#include "editquerymodel.h"

#include <QDir>
#include <QMessageBox>
#include <QSqlRecord>
#include <qsqlquery.h>

editQueryModel::editQueryModel(QObject *parent) : QSqlQueryModel(parent)
{
    QDir path;
    if ( path.exists("Database") == false )
    {
        path.mkdir("Database");
    }
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(".\\Database\\dictionary_ll.db");
    db.open();
    if ( !db.isOpen() )
    {
        qDebug()<<"open err"<<db.lastError();
    }
    QSqlQuery query;
    if ( db.tables().contains("dictionary") == true )
    {
        qDebug()<<"表已经存在";
        /* 兼容老表 */
        QString sqlSelectTable = QString( "select * from dictionary;" );
        if ( !query.exec( sqlSelectTable ) )
        {
            qDebug()<<sqlSelectTable;
            qDebug()<<"sqlSelectTable"<<db.lastError();
        }
        if ( query.record().contains("WordClass") == false )
        {
            /* add new colomn */
            QString sqlAddColumnTable = QString( "alter table dictionary add column WordClass TEXT;" );
            if ( !query.exec( sqlAddColumnTable ) )
            {
                qDebug()<<sqlAddColumnTable;
                qDebug()<<"sqlAddColumnTable"<<db.lastError();
                qDebug()<<"sqlAddColumnTable"<<db.lastError().text();
            }
        }
        else
        {
            qDebug()<<"新列已经添加";
        }
    }
    else
    {
        QString sqlCreateTable = QString( "create table dictionary(id integer primary key autoincrement,"
                                  "Chinese TEXT,"
                                  "English TEXT,"
                                  "WordClass TEXT);");
        if ( !query.exec( sqlCreateTable ) )
        {
            qDebug()<<sqlCreateTable;
            qDebug()<<"create table"<<db.lastError();
        }
    }
    setQuery( "select * from dictionary;" );
}

editQueryModel::~editQueryModel()
{
    if ( db.isOpen() )
    {
        db.close();
        qDebug()<<"db.close()";
    }
    qDebug()<<"析构函数";
}

bool editQueryModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    qDebug()<<"role="<<role;
    /* [1] 判断是否位有效名 */
    if (( index.column() < 1 )||( index.column() > 3 ))
    {
        return false;
    }    
    if ( celldata.data() == value )
    {
        qDebug()<<"Data not change";
        return true;
    }
    QMessageBox message(QMessageBox::NoIcon,QString::fromUtf8("提示"),QString::fromUtf8("是否更改本行数据？"),
                        QMessageBox::Yes | QMessageBox::No,NULL);
    if(message.exec() == QMessageBox::No)
    {
        return true;
    }
    QModelIndex prinmaryIndex = editQueryModel::index( index.row(), 0 ) ;
    int id = this->data( prinmaryIndex ).toInt();
    this->clear();
    bool ok=false;
    if ( index.column() == 1 )
    {
         ok = setChinese( id, value.toString() );
         refresh();
    }
    else if ( index.column() == 2 )
    {
         ok = setEnglish( id, value.toString() );
         refresh();
    }
    else if ( index.column() == 3 )
    {
        ok = setWordClass( id, value.toString() );
        refresh();
    }
    return ok;
}
Qt::ItemFlags editQueryModel::flags(const QModelIndex &index) const
{
    Qt::ItemFlags flag = QSqlQueryModel::flags( index );

//    if (( index.column() >= 1 )&&( index.column() <= 3 ))
//    {
//        flag|=Qt::ItemIsEditable;
//    }
    return flag;
}


/* n. v. adj. adv. art. conj. prep. pron. num.  int. */
bool editQueryModel::deleteData(int row)
{
    int id  = editQueryModel::index( row, 0 ).data().toInt() ;
    QString Chinese = editQueryModel::index( row, 1 ).data().toString() ;
    QString English = editQueryModel::index( row, 2 ).data().toString() ;
    QString WordClass = editQueryModel::index( row, 3 ).data().toString() ;
    QSqlQuery query;
    QString sqlDelete = QString( "delete from dictionary where id=%1 AND Chinese='%2' AND English='%3';" )
                        .arg( id ).arg( Chinese ).arg( English );
    if ( !query.exec( sqlDelete ) )
    {
        qDebug()<<sqlDelete;
        qDebug()<<"sqlDelete db err"<<db.lastError();
    }
    refresh();
}

bool editQueryModel::addData(QString &Chinese, QString &English, QString &WordClass)
{
    bool addSucceed = false;
    if (( Chinese.count() == 0 )||( English.count() == 0 ))
    {
        qDebug()<<"参数不全";
        emit addDataFinish( addSucceed );
        return false;
    }
    QSqlQuery query;
    QString sqlInsert = QString("insert into dictionary( Chinese,English,WordClass) "
                                "values('%1','%2','%3');").arg( Chinese).arg( English ).arg(WordClass);
    if ( !query.exec( sqlInsert ) )
    {
        qDebug()<<sqlInsert;
        qDebug()<<"insert into data err"<<db.lastError();
        addSucceed = false ;
    }
    else
    {
        addSucceed = true ;
    }
    emit addDataFinish( addSucceed );
    refresh();
    return true;
}

void editQueryModel::refresh()
{
    this->setQuery( "select * from dictionary;" );
    emit sendRefreshTable();
}

bool editQueryModel::setChinese(int id, const QString &Chinese)
{
    qDebug()<<__LINE__<<"id="<<id<<" name="<<Chinese;
    QSqlQuery query;
    query.prepare( "update dictionary set Chinese = ? where id = ?" );
    query.addBindValue( Chinese );
    query.addBindValue( id );
    return query.exec();
}

bool editQueryModel::setEnglish(int id, const QString &English)
{
    qDebug()<<__LINE__<<"id="<<id<<" name="<<English;
    QSqlQuery query;
    query.prepare( "update dictionary set English = ? where id = ?" );
    query.addBindValue( English );
    query.addBindValue( id );
    return query.exec();
}

/* n. v. adj. adv. art. conj. prep. pron. num. int. *. */
bool editQueryModel::setWordClass(int id, const QString &WordClass)
{
    qDebug()<<__LINE__<<"id="<<id<<" name="<<WordClass;
    QSqlQuery query;
    query.prepare( "update dictionary set WordClass = ? where id = ?" );
    query.addBindValue( WordClass );
    query.addBindValue( id );
    return query.exec();
}

void editQueryModel::saveOldData(const QModelIndex &index)
{
    celldata = index;
    qDebug()<<celldata;
}

void editQueryModel::changeWordClassSlot( QString &WordClass )
{
    if ( celldata.data().toString() == WordClass )
    {
        qDebug()<<"Data not change";
        return;
    }
    QMessageBox message(QMessageBox::NoIcon,QString::fromUtf8("提示"),QString::fromUtf8("是否更改本行数据？"),
                        QMessageBox::Yes | QMessageBox::No,NULL);
    if(message.exec() == QMessageBox::No)
    {
        return;
    }
    QModelIndex prinmaryIndex = editQueryModel::index( celldata.row(), 0 ) ;
    int id = data( prinmaryIndex ).toInt();
    clear();
    setWordClass( id, WordClass );
    refresh();

}



